package com.pig4cloud.pigx.contract.executer.order.migrator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pigx.common.customize.exception.MqNotAckException;
import com.pig4cloud.pigx.contract.entity.ContractOrder;
import com.pig4cloud.pigx.contract.enums.ContractOrderEnum;
import com.pig4cloud.pigx.contract.mapper.ContractOrderHistoryMapper;
import com.pig4cloud.pigx.contract.mapper.ContractOrderMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 历史订单迁移
 *
 * @since 2022/9/20 16:22
 */
@Component
@AllArgsConstructor
public class OrderMigrator {

	private final ContractOrderMapper contractOrderMapper;
	private final ContractOrderHistoryMapper contractOrderHistoryMapper;

	public final String ERROR_MSG = "历史订单迁移失败";

	/**
	 * 订单id
	 *
	 * @param idList idList
	 * @since 2022/9/20 16:23
	 */
	public void migrator(List<Long> idList) {
		if (CollectionUtils.isEmpty(idList)) {
			return;
		}

		// 查询订单
		QueryWrapper<ContractOrder> query = new QueryWrapper<>();
		query.lambda()
				.in(ContractOrder::getId, idList)
				.notIn(ContractOrder::getStatus, ContractOrderEnum.Status.ON_GOING.getValue(),
						ContractOrderEnum.Status.PARTIAL_DEAL.getValue());

		List<ContractOrder> list = contractOrderMapper.selectList(query);
		if (CollectionUtils.isEmpty(list)) {
			return;
		}

		// 历史订单表新增
		if (contractOrderHistoryMapper.migrateBatch(list) != list.size()) {
			throw new MqNotAckException(ERROR_MSG);
		}

		// 获得实际迁移的订单id
		List<Long> actualIdList = list.stream()
				.map(ContractOrder::getId)
				.collect(Collectors.toList());

		// 订单表删除
		if (contractOrderMapper.deleteBatchIds(actualIdList) != list.size()) {
			throw new MqNotAckException(ERROR_MSG);
		}
	}
}
